package com.lanou.service.impl;

import com.alibaba.fastjson.JSON;
import com.lanou.service.UserService;
import com.lanou.utils.HttpClientUtils;
import com.lanou.utils.ShiHuiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by QuChao on 2018/12/4
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${SSO_CHECK_LOGIN_STATUS_URL}")
    private String SSO_CHECK_LOGIN_STATUS_URL;

    @Value("${SSO_LOGIN_URL}")
    private String SSO_LOGIN_URL;

    @Value("${SSO_LOGOUT_URL}")
    private String SSO_LOGOUT_URL;

    @Value("${SSO_REGISTER_URL}")
    private String SSO_REGISTER_URL;

    @Override
    public Map<String, Object> checkLoginStatus(String token) {
        String raw = HttpClientUtils.getRaw(SSO_CHECK_LOGIN_STATUS_URL + token);
        Map map = JSON.parseObject(raw, Map.class);
        if (map.get("status").equals(200)) {
            return ShiHuiResult.ok(map.get("data"));
        } else {
            return ShiHuiResult.error(400, "用户未登录");
        }
    }

    @Override
    public Map<String, Object> login(Map<String, String> map) {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("username", map.get("userName"));
        map1.put("password", map.get("userPwd"));
        String post = HttpClientUtils.post(SSO_LOGIN_URL, map1);
        if (post != null) {
            Map map3 = JSON.parseObject(post, Map.class);
            return map3;
        } else {
            return null;
        }
    }

    @Override
    public boolean logout(String token) {
        String raw = HttpClientUtils.getRaw(SSO_LOGOUT_URL + token);
        Map map = JSON.parseObject(raw, Map.class);
        return map.get("status").equals(200) ? true : false;
    }

    @Override
    public boolean register(String userName, String userPwd) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", userName);
        map.put("password", userPwd);
        String post = HttpClientUtils.post(SSO_REGISTER_URL, map);
        Map map1 = JSON.parseObject(post, Map.class);
        return map1.get("status").equals(200) ? true : false;
    }
}
